Duplicated type casts (DTC)

Description:

If you need to access components of some more specific class than the one that a reference variable has, you will have to explicitly cast the reference. If you access more than one component, then type cast has to be repeated multiple times. This complicates the code and makes it less efficient. In this case, it is better to declare an extra local variable of a proper type and assign the casted reference to it. You can also use the C# operator as which performs check and cast at the same time.

The option, Maximal number of casts, defines the maximal number of duplicated type casts that will be allowed by DTC. It is set to 1 by default, which means that a warning message will be generated for every duplicated cast.

Incorrect:

if (obj is string) { 
    return ((string) obj).Length == 0 || ((string) obj)[0] == '#';
}

Correct:

string str = obj as string;
if (str != null) { 
    return str.Length == 0 || str[0] == '#';
}